package cn.yueranzs.system.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.yueranzs.handler.BusinessException;
import cn.yueranzs.login.common.DataUtil;
import cn.yueranzs.response.Result;
import cn.yueranzs.response.ResultCode;
import cn.yueranzs.response.ResultPage;
import cn.yueranzs.response.UserResultCode;
import cn.yueranzs.system.dto.user.AssignRoleChangeDto;
import cn.yueranzs.system.dto.user.UserChangeDto;
import cn.yueranzs.system.dto.user.UserQueryDto;
import cn.yueranzs.system.pojo.User;
import cn.yueranzs.system.service.UserService;
import cn.yueranzs.utils.PaginationUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author yueranzs
 * @since 2021-11-04
 */
@Api(tags = "用户控制器")
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 分页查询用户列表
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @ApiOperation(value = "分页查询用户列表",notes = "根据传入的分页查询用户列表")
    @GetMapping("/findUserList")
    public Result findUserList(UserQueryDto dto){
        //对用户进行分页，泛型中注入返回类型
        Page page = PaginationUtil.getNewPage(dto.getCurrentPage(), dto.getPageSize());
        User user = DataUtil.setData(dto,User.class);
        ResultPage userPage = userService.findUserList(user, page);
        return Result.successData(userPage);
    }

    /**
     * 角色授权：授权代码需要加ROLE_前缀，controller上使用时不要加前缀
     * 权限授权：设置和使用时，名称保持一致即可
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @ApiOperation(value = "测试一下",notes = "测试一下")
    @GetMapping("/test")
    public Result test(){
        return Result.successData("hahah");
    }

    /**
     * 角色授权：授权代码需要加ROLE_前缀，controller上使用时不要加前缀
     * 权限授权：设置和使用时，名称保持一致即可
     * @param dto
     * @return
     */

    @PreAuthorize("hasRole('admin')")
    @ApiOperation(value = "新增用户",notes = "根据传入的参数新增用户")
    @PostMapping("/insertUser")
    public Result insertUser(@RequestBody UserChangeDto dto){
        try {
            User user = DataUtil.setData(dto,User.class);
            userService.insertUser(user);
            return Result.ok(ResultCode.SAVESUCCESS.getCode(), ResultCode.SAVEERROR.getMessage());
        }catch (BusinessException e){
            return Result.error(e.getCode(),e.getErrMsg());
        }
    }

    @PreAuthorize("hasRole('admin')")
    @ApiOperation(value = "删除用户",notes = "根据传入的参数删除用户")
    @PostMapping("/deleteUser/{id}")
    public Result deleteUser(@PathVariable("id") Long id){
        if (ObjectUtil.isEmpty(id)) {
            return Result.error(UserResultCode.USER_NOT_ID.getCode(),UserResultCode.USER_NOT_ID.getMessage());
        }
        try {
            userService.deleteUser(id);
            return Result.ok(ResultCode.DELETESUCCESS.getCode(),ResultCode.DELETESUCCESS.getMessage());
        }catch (BusinessException e){
            return Result.error(e.getCode(),e.getErrMsg());
        }
    }

    @PreAuthorize("hasRole('admin')")
    @ApiOperation(value = "修改用户",notes = "根据传入的参数修改用户")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserChangeDto dto){
        if (ObjectUtil.isEmpty(dto.getId())) {
            return Result.error(UserResultCode.USER_NOT_ID.getCode(),UserResultCode.USER_NOT_ID.getMessage());
        }
        try {
            User user = DataUtil.setData(dto,User.class);
            user.setAvatar(null);
            userService.updateUser(user);
            return Result.ok(ResultCode.UPDATESUCCESS.getCode(),ResultCode.UPDATESUCCESS.getMessage());
        }catch (BusinessException e){
            return Result.error(e.getCode(),e.getErrMsg());
        }
    }

    @PreAuthorize("hasRole('admin')")
    @ApiOperation(value = "导出用户",notes = "根据传入的参数导出用户列表")
    @PostMapping("/excelUserList")
    public void excelUserList(HttpServletResponse response, @RequestBody UserQueryDto dto){
        User user = DataUtil.setData(dto,User.class);
        userService.excelUserList(response,user);
    }

    @PreAuthorize("hasRole('admin')")
    @ApiOperation(value = "分配角色",notes = "分配角色")
    @PostMapping("/assignRole")
    public Result assignRole(@RequestBody AssignRoleChangeDto dto){
        if (ObjectUtil.isEmpty(dto.getUserId())) {
            return Result.error(UserResultCode.USER_NOT_ID.getCode(),UserResultCode.USER_NOT_ID.getMessage());
        }
        try {
            userService.assignRole(dto);
            return Result.ok(ResultCode.UPDATESUCCESS.getCode(),ResultCode.UPDATESUCCESS.getMessage());
        }catch (BusinessException e){
            return Result.error(e.getCode(),e.getErrMsg());
        }
    }

}

